﻿using System;
using Saisie_des_prélèvements.ViewModels;
using Saisie_des_prélèvements.Models;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Popups;
using System.Net.Http;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Saisie_des_prélèvements.Common;
using Windows.Foundation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace Saisie_des_prélèvements.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class LoginPage : Page
    {

        public LoginPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            VerifyData();
        }

        private async void txtLogin_Click(object sender, RoutedEventArgs e)
        {
            App.CurrentUserId = (new UserViewModel()).GetUserID(txtUser.Text, txtPassword.Password);
            
            if (App.CurrentUserId == 0)
            {
                // Create the message dialog and set its content; it will get a default "Close" button since there aren't any other buttons being added
                var messageDialog = new MessageDialog(new msg().login_NotCorrectUser);

                // Show the message dialog and wait
                await messageDialog.ShowAsync();
                
            }
            else
                this.Frame.Navigate(typeof(BasicPage));
        }

        private async void VerifyData()
        {
            string uri = App.AppUri;

            using (var db = new SQLite.SQLiteConnection(App.DBPath))
            {
                txtVerifData.Text = string.Format(new msg().login_Initialization, (char)13);
               
                #region Setting
                if (db.Table<k_setting>().Count() == 0)
                {
                    // Add seed k_setting
                    var prod = new k_setting()
                    {
                        client_seq = "00001",
                        taken_seq = "00001"
                    };

                    db.Insert(prod);

                    if (!await ValidateUrl(string.Format("{0}{1}", uri, "GetAllUser")))
                    {
                        txtVerifData.Text = string.Format(new msg().login_RecoveryFail, (char)13); //string.Format("Can't connect to server {0}", uri);

                        prrVerify.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                        btnDetail.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                        btnExit.Visibility = Windows.UI.Xaml.Visibility.Visible;
                        return;
                    }
                }
                #endregion Setting

                if (db.Table<k_user>().Count() == 0)
                {
                    txtVerifData.Text = string.Format(new msg().login_Recovery, (char)13);

                    try
                    {
                        //Kalficom.Service1Client myService = new Kalficom.Service1Client();
                        var client = new HttpClient();

                        //HttpResponseMessage m = await client.GetAsync(new Uri(string.Format("{0}{1}", uri, "GenerateTakenSchedule")));
                        #region User

                        string responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllUser")));
                        var list_user = (List<k_user>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_user>));
                        db.InsertAll(list_user);

                        #endregion User

                        #region ClientTaken

                        if (db.Table<k_client_taken>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllClientTaken")));
                            var list_client = (List<k_client_taken>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_client_taken>));
                            foreach (k_client_taken k in list_client) db.InsertOrReplace(k);
                        }
                        #endregion ClientTaken

                        #region ZoneGeographic

                        if (db.Table<k_zone_geographic>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllZone")));
                            var list_zone = (List<k_zone_geographic>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_zone_geographic>));
                            db.InsertAll(list_zone);
                        }
                        #endregion ZoneGeographic

                        #region NTIERS_X
                        if (db.Table<NTIERS_X>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllNTIERS_X")));
                            var list_NTIERS_X = (List<NTIERS_X>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<NTIERS_X>));
                            db.InsertAll(list_NTIERS_X);
                        }

                        #endregion NTIERS_X

                        #region Contract

                        if (db.Table<k_contract>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllContract")));
                            var list_contract = (List<k_contract>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_contract>));
                            db.InsertAll(list_contract);
                        }
                        #endregion Contract

                        #region SystemParameter

                        if (db.Table<k_system_parameter>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllSystemParameter")));
                            var list_system = (List<k_system_parameter>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_system_parameter>));
                            db.InsertAll(list_system);
                        }
                        #endregion SystemParameter

                        #region Taken

                        if (db.Table<k_taken>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllTaken")));
                            var list = (List<k_taken>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_taken>));

                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllTakenAnalyze")));
                            var list_analyze = (List<k_taken_analyze>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_taken_analyze>));

                            foreach (k_taken k in list)
                            {
                                k.taken_id_main = k.taken_id;
                                db.Insert(k);

                                List<k_taken_analyze> anas = new List<k_taken_analyze>();
                                foreach (k_taken_analyze ana in list_analyze.Where(a => a.taken_id == k.taken_id_main))
                                {
                                    
                                    ana.taken_id = k.taken_id;
                                    ana.sch_id = k.sch_id;
                                    anas.Add(ana);
                                }

                                db.InsertAll(anas);
                            }
                        }
                        #endregion Taken

                        #region TakenAnalyze
                        //if (db.Table<k_taken_analyze>().Count() == 0)
                        //{
                        //    responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllTakenAnalyze")));
                        //    var list_analyze = (List<k_taken_analyze>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<k_taken_analyze>));
                        //    db.InsertAll(list_analyze);
                        //}
                        #endregion TakenAnalyze

                        #region NPRODUIT
                        if (db.Table<NPRODUIT>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllNproduit")));
                            var list_NPRODUIT = (List<NPRODUIT>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<NPRODUIT>));
                            db.InsertAll(list_NPRODUIT);
                        }
                        #endregion NPRODUIT

                        #region PLANCOUNT
                        if (db.Table<PLANCONT>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllPlanCont")));
                            var list_PLANCONT = (List<PLANCONT>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<PLANCONT>));
                            db.InsertAll(list_PLANCONT);
                        }
                        #endregion PLANCOUNT

                        #region SECTEURS
                        if (db.Table<SECTEURS>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllSecteur")));
                            var list_SECTEURS = (List<SECTEURS>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<SECTEURS>));
                            db.InsertAll(list_SECTEURS);
                        }
                        #endregion SECTEURS

                        #region ANALYSES
                        if (db.Table<ANALYSES>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllAnalyse")));
                            var list_ANALYSES = (List<ANALYSES>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<ANALYSES>));
                            db.InsertAll(list_ANALYSES);
                        }
                        #endregion ANALYSES

                        #region ANAPLAN
                        if (db.Table<ANAPLAN>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllAnaPlan")));
                            var list_ANAPLAN = (List<ANAPLAN>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<ANAPLAN>));
                            db.InsertAll(list_ANAPLAN);
                        }
                        #endregion ANAPLAN

                        #region ANAPRD
                        if (db.Table<ANAPRD>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllAnalyseProduit")));
                            var list_ANAPRD = (List<ANAPRD>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<ANAPRD>));
                            db.InsertAll(list_ANAPRD);
                        }
                        #endregion ANAPRD

                        #region IDENT01
                        if (db.Table<IDENT01>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent01")));
                            var list_IDENT01 = (List<IDENT01>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT01>));
                            db.InsertAll(list_IDENT01);
                        }
                        #endregion IDENT01

                        #region IDENT02
                        if (db.Table<IDENT02>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent02")));
                            var list_IDENT02 = (List<IDENT02>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT02>));
                            db.InsertAll(list_IDENT02);
                        }
                        #endregion IDENT02

                        #region IDENT03
                        if (db.Table<IDENT03>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent03")));
                            var list_IDENT03 = (List<IDENT03>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT03>));
                            db.InsertAll(list_IDENT03);
                        }
                        #endregion IDENT03

                        #region IDENT04
                        if (db.Table<IDENT04>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent04")));
                            var list_IDENT04 = (List<IDENT04>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT04>));
                            db.InsertAll(list_IDENT04);
                        }
                        #endregion IDENT04

                        #region IDENT05
                        if (db.Table<IDENT05>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent05")));
                            var list_IDENT05 = (List<IDENT05>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT05>));
                            db.InsertAll(list_IDENT05);
                        }
                        #endregion IDENT05

                        #region IDENT06
                        if (db.Table<IDENT06>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent06")));
                            var list_IDENT06 = (List<IDENT06>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT06>));
                            db.InsertAll(list_IDENT06);
                        }
                        #endregion IDENT06

                        #region IDENT07
                        if (db.Table<IDENT07>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent07")));
                            var list_IDENT07 = (List<IDENT07>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT07>));
                            db.InsertAll(list_IDENT07);
                        }
                        #endregion IDENT07

                        #region IDENT08
                        if (db.Table<IDENT08>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent08")));
                            var list_IDENT08 = (List<IDENT08>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT08>));
                            db.InsertAll(list_IDENT08);
                        }
                        #endregion IDENT08

                        #region IDENT09
                        if (db.Table<IDENT09>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent09")));
                            var list_IDENT09 = (List<IDENT09>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT09>));
                            db.InsertAll(list_IDENT09);
                        }
                        #endregion IDENT09

                        #region IDENT10
                        if (db.Table<IDENT10>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent10")));
                            var list_IDENT10 = (List<IDENT10>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT10>));
                            db.InsertAll(list_IDENT10);
                        }
                        #endregion IDENT10

                        #region IDENT11
                        if (db.Table<IDENT11>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent11")));
                            var list_IDENT11 = (List<IDENT11>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT11>));
                            db.InsertAll(list_IDENT11);
                        }
                        #endregion IDENT11

                        #region IDENT12
                        if (db.Table<IDENT12>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllIdent12")));
                            var list_IDENT12 = (List<IDENT12>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<IDENT12>));
                            db.InsertAll(list_IDENT12);
                        }
                        #endregion IDENT12

                        #region PTPREL
                        if (db.Table<PTPREL>().Count() == 0)
                        {
                            responseBodyAsText = await client.GetStringAsync(new Uri(string.Format("{0}{1}", uri, "GetAllPtprel")));
                            var list_PTPREL = (List<PTPREL>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseBodyAsText, typeof(List<PTPREL>));
                            db.InsertAll(list_PTPREL);
                        }
                        #endregion PTPREL

                        //VerifyTakenCollection();

                        txtVerifData.Text = string.Format(new msg().login_RecoverySuccess, (char)13);
                        prrVerify.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                        btnOK.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    }
                    catch (Exception ex)
                    {
                        txtVerifData.Text = string.Format(new msg().login_RecoveryFail, (char)13);
                        txtVerifDetial.Text = ex.Message;
                        prrVerify.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                        btnDetail.Visibility = Windows.UI.Xaml.Visibility.Visible;
                        btnExit.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    }

                }
                else
                {
                    stpVerifyData.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    stpLogin.Visibility = Windows.UI.Xaml.Visibility.Visible;
                }
            }
        }


        private void VerifyTakenCollection()
        {
            //prrVerify.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            //prbTaken.Visibility = Windows.UI.Xaml.Visibility.Visible;
            using (var db = new SQLite.SQLiteConnection(App.DBPath))
            {
                List<k_taken> takens = db.Table<k_taken>().ToList();
                List<k_taken_analyze> analyzes = db.Table<k_taken_analyze>().ToList();
                int RecordCount = 1;
                
                foreach (k_taken taken in takens)
                {
                    txtVerifData.Text = string.Format(new msg().login_VertifyTaken, RecordCount, takens.Count);
                    txtVerifData.Dispatcher.ProcessEvents(Windows.UI.Core.CoreProcessEventsOption.ProcessAllIfPresent);
                    if (taken.taken_date != null && taken.taken_date.Value.Date < DateTime.Now.Date && taken.taken_point_day > 0)
                    {
                        for (DateTime? dt = taken.taken_date.Value.Date.AddDays((double)taken.taken_point_day); dt <= DateTime.Now.Date.AddDays((double)taken.taken_point_day); dt = dt.Value.AddDays((double)taken.taken_point_day))
                        {
                            k_taken k = new k_taken()
                            {
                                client_taken_id = taken.client_taken_id,
                                amount = taken.amount,
                                comment = taken.comment,
                                date_create = taken.date_create,
                                date_extraction = taken.date_extraction,
                                days_taken = taken.days_taken,
                                export_client_id = taken.export_client_id,
                                months_taken = taken.months_taken,
                                prod_code = taken.prod_code,
                                reason_delete = taken.reason_delete,
                                sample_number = taken.sample_number,
                                status = taken.status,
                                surv_code = taken.surv_code,
                                taken_code = taken.taken_code,
                                taken_comment = taken.taken_comment,
                                taken_date = taken.taken_date,
                                taken_date_last = taken.taken_date_last,
                                taken_date_next = dt,
                                taken_point_code = taken.taken_point_code,
                                taken_point_day = taken.taken_point_day,
                                taken_point_label = taken.taken_point_label,
                                taken_point_modifiable = taken.taken_point_modifiable,
                                taken_type = taken.taken_type,
                                years_taken = taken.years_taken
                            };

                            db.Insert(k);

                            List<k_taken_analyze> new_analyzes = new List<k_taken_analyze>();
                            foreach (k_taken_analyze analyze in analyzes.Where(a => a.taken_id == taken.taken_id))
                            {
                                analyze.taken_id = k.taken_id;
                                new_analyzes.Add(analyze);
                            }
                            db.InsertAll(new_analyzes);
                        }
                    }
                    
                    RecordCount++;
                }
            }
            
            
        }


        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            App.Current.Exit();
        }

        private void btnDetail_Click(object sender, RoutedEventArgs e)
        {
            stpVerifyDetail.Visibility = Windows.UI.Xaml.Visibility.Visible;
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            stpVerifyData.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            stpLogin.Visibility = Windows.UI.Xaml.Visibility.Visible;
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            App.Current.Exit();
        }

        private void txtPassword_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
        {
            //if (e.Key == Windows.System.VirtualKey.Enter)
            //    txtLogin_Click(null, null);
        }

        internal static async Task<bool> ValidateUrl(string url)
        {
            try {
                Uri validUri;
                if (Uri.TryCreate(url, UriKind.Absolute, out validUri))
                {
                    var client = new HttpClient();

                    var response = await client.GetAsync(validUri, HttpCompletionOption.ResponseHeadersRead);
                    return response.IsSuccessStatusCode;
                }
            }
            catch
            {
                return false;
            }
            return false;
        }
    }
}
